{% extends "admin/change_form.html" %}

{% block form_top %}
<div id="custom_alert" title="Erro no formulário!" class="disabled_alert">
	<p>Nenhuma Pergunta válida inserida.<br/>
	   Preencha pelo menos uma Pergunta válida e tente novamente Abrir Chamado.
	</p>
</div>

<div id="custom_blank_alert" title="Erro no formulário!" class="disabled_alert">
	<p>Existem Perguntas ou Respostas em branco!<br/>
	   Preencha-as corretamente e tente novamente.
	</p>
</div>

<div id="custom_confirm" title="Confirmação" class="disabled_confirm">
	<p>
		<span id="span_confirm" class="ui-icon ui-icon-alert">
		</span>Deseja realmente Abrir este Chamado?
	</p>
</div>

<div id="custom_edit_confirm" title="Confirmação" class="disabled_confirm">
	<p>
		<span id="span_confirm" class="ui-icon ui-icon-alert">
		</span>Deseja realmente salvar as modificações?
	</p>
</div>

<div id="back_confirm" title="Confirmação" class="disabled_confirm">
	<p>
		<span id="span_confirm" class="ui-icon ui-icon-alert">
		</span>Deseja voltar à página anterior?<br/>
			   Modificações não serão salvas.
	</p>
</div>


  <link rel="stylesheet" type="text/css" href="/static/css/custom.css"/>
  <link rel="stylesheet" type="text/css" href="/static/css/jquery-ui-1.8.21.custom.css" />
  <script type="text/javascript" src="/static/js/jquery-1.7.2.min.js" ></script>
  <script type="text/javascript" src="/static/js/jquery-ui-1.8.21.custom.min.js" ></script>
  <script type="text/javascript">
	<!--
	//TODO
	//Tratar edicao de chamados
	//funcao para travar campos em comum
	//e funcao para destravar
	//
	
		var operation = '';
		window.onload = function(){
    		var url = window.location.pathname.split('/').toString();
    		if(url.indexOf('add') != -1){
    			operation = 'add';
    			killAlert();
    			killConfirm();
    			renderAdd();
    		}
    		else{
    			operation = 'edit';
    			renderEdit();
    			enableAccordion();
    		}
		}
		
		function renderAdd(){
			changeAddTopText();
			fillClient();
			lockAddFields();
			removeExtraButtons();
			changeSaveLabel();
			changeSubmitBehavior();
			lockAllDates();
			placeQuestionsAdder();
		
		}
		
		function renderEdit(){
			checkStatus();
			placeQuestionsAdder();
			changeEditTopText();
			changeEditSubmition();
			lockEditFields();
			handleFields();
			removeExtraButtons();
			handleButtons();
			placeAnswerAdder()
		
		}
		
		function hideSeqs(){
			$('.field-seq_number').addClass("disabled");
		}
		
		function fillQuestionSeq(){
			var questions = $('div.dynamic-pergunta_set');
	        for(var i = 0; i < questions.length; i++){
	            var seq_number = $(questions[i]).find('div.field-seq_number > div').find('input.vIntegerField')[0].value;
	            if(seq_number == ''){
	                var inline_label = $(questions[i]).find('span.inline_label')[0].innerHTML;
	                inline_label = inline_label.split('#')[1];
	                $(questions[i]).find('div.field-seq_number > div').find('input.vIntegerField')[0].value = parseInt(inline_label);
	            }
	        }
        }
        
        function fillAnswerSeq(){
			var answers = $('div.dynamic-resposta_set');
	        for(var i = 0; i < answers.length; i++){
	            var seq_number = $(answers[i]).find('div.field-seq_number > div').find('input.vIntegerField')[0].value;
	            if(seq_number == ''){
	                var inline_label = $(answers[i]).find('span.inline_label')[0].innerHTML;
	                inline_label = inline_label.split('#')[1];
	                $(answers[i]).find('div.field-seq_number > div').find('input.vIntegerField')[0].value = parseInt(inline_label);
	            }
	        }
        }
		
		function changeAddTopText(){
			$('#content').find('h1')[0].id = "toptext";
			$('#toptext').html("Formulário para abertura de Chamado");
		}
		
		function changeEditTopText(){
			$('#content').find('h1')[0].id = "toptext";
			$('#toptext').html("Formulário para edição de Chamado");
		}
		
		function fillClient(){
			if('{{ user.first_name }}' != '' && '{{ user.last_name }}' != ''){
				document.getElementById("id_cliente").value = '{{ user.first_name }} ' + '{{ user.last_name }}';
			}
			else{
				document.getElementById("id_cliente").value = '{{ user.username }}';
			}
		}
		
		function lockAddFields(){
			$('#id_cliente').attr("disabled", "disabled");
			$('#id_cliente').addClass("disabled");
            $('#id_grupo').attr("disabled", "disabled");
            $('#id_grupo').addClass("disabled");
			$('#id_abertura').attr("disabled", "disabled");
			$('#id_abertura').addClass("disabled");
			$('#id_atualizacao').attr("disabled", "disabled");
			$('#id_atualizacao').addClass("disabled");
			$('#id_status').attr("disabled", "disabled");
			$('#id_status').addClass("disabled");
			$('.field-abertura').find("span.datetimeshortcuts").addClass("disabled");
			$('.field-atualizacao').find("span.datetimeshortcuts").addClass("disabled");
			$('.field-fechamento').addClass("disabled");
		}
		
		function lockEditFields(){
			$('#id_cliente').attr("disabled", "disabled");
			$('#id_cliente').addClass("disabled");
            $('#id_grupo').attr("disabled", "disabled");
            $('#id_grupo').addClass("disabled");
			$('#id_tipo').attr("disabled", "disabled");
			$('#id_tipo').addClass("disabled");
			$('#id_abertura').attr("disabled", "disabled");
			$('#id_abertura').addClass("disabled");
			$('#id_atualizacao').attr("disabled", "disabled");
			$('#id_atualizacao').addClass("disabled");
			$('.field-abertura').find("span.datetimeshortcuts").addClass("disabled");
			$('.field-atualizacao').find("span.datetimeshortcuts").addClass("disabled");
		}
		
		function unlockAddFields(){
			$('#id_cliente').attr("disabled", false);
			$('#id_cliente').removeClass("disabled");
            $('#id_grupo').attr("disabled", "false");
            $('#id_grupo').removeClass("disabled");
			$('#id_abertura').attr("disabled", false);
			$('#id_abertura').removeClass("disabled");
			$('#id_atualizacao').attr("disabled", false);
			$('#id_atualizacao').removeClass("disabled");
			$('#id_status').attr("disabled", false);
			$('#id_status').removeClass("disabled");
			$('.field-abertura').find("span.datetimeshortcuts").removeClass("disabled");
			$('.field-atualizacao').find("span.datetimeshortcuts").removeClass("disabled");
			$('.field-fechamento').removeClass("disabled");
			unlockQuestionsFields();
			
			//submete form apos destravar campos
			document.forms['chamado_form'].submit();
		}
		
		function unlockEditFields(){
			$('#id_cliente').attr("disabled", false);
			$('#id_cliente').removeClass("disabled");
            $('#id_grupo').attr("disabled", "false");
            $('#id_grupo').removeClass("disabled");
			$('#id_abertura').attr("disabled", false);
			$('#id_abertura').removeClass("disabled");
			$('#id_tipo').attr("disabled", false);
			$('#id_tipo').removeClass("disabled");
			$('#id_atualizacao').attr("disabled", false);
			$('#id_atualizacao').removeClass("disabled");
			$('#id_status').attr("disabled", false);
			$('#id_status').removeClass("disabled");
			$('.field-abertura').find("span.datetimeshortcuts").removeClass("disabled");
			$('.field-atualizacao').find("span.datetimeshortcuts").removeClass("disabled");
			$('.field-fechamento').removeClass("disabled");
			$('.vLargeTextField').removeClass("disabled");
			$('.vLargeTextField').attr("disabled", false);
			$('.field-data').find("span.datetimeshortcuts").removeClass("disabled");
			$('.vDateField').removeClass("disabled");
			$('.vDateField').attr("disabled", false);
			
			//submete form apos destravar os campos
			document.forms['chamado_form'].submit();
		}
		
		function removeExtraButtons(){
			if(operation == "add"){
				$('input[name=_addanother]')[0].id = "addanother";
			}
			$('input[name=_continue]')[0].id = "continue";
			$('#addanother').addClass("disabled");
			$('#continue').addClass("disabled");
		}
		
		function changeSaveLabel(){
			$('input[name=_save]')[0].id = "save";
			$('#save')[0].value = "Abrir Chamado";
		}		
		
		function killAlert(){
			$('#custom_alert:ui-dialog').dialog("destroy");
		}
		
		function killConfirm(){
			$('#custom_confirm:ui-dialog').dialog("destroy");
		}
		
		function lockAllDates(){
			$('.vDateField').attr("disabled", "disabled");
			$('.vDateField').addClass("disabled");
			$('.datetimeshortcuts').addClass("disabled");
			var fechamento = $('#id_fechamento');
			if(fechamento[0].value == ""){
				fechamento.attr("disabled", false);
				fechamento.removeClass("disabled");
				$('div.field-fechamento > div > span').removeClass("disabled");
			}
		}
		
		function placeQuestionsAdder(){
			var addRows = $('div.add-row > a');
			for(var i=0; i<addRows.length; i++){
				if(addRows[i].innerHTML.indexOf('Pergunta') == -1){
					addRows.splice(i);		
				}
			}
			addRows.attr("onclick", "javascript:lockAllDates();javascript:hideSeqs();" +
									 "javascript:fillQuestionSeq()");
		}
		
		function placeAnswerAdder(){
			var addRows = $('div.add-row > a');
			for(var i=0; i<addRows.length; i++){
				if(addRows[i].innerHTML.indexOf('Resposta') == -1){
					addRows.splice(i);		
				}
			}
			addRows.attr("onclick", "javascript:lockAllDates();javascript:hideSeqs();" +
									"javascript:fillAnswerSeq()");
		}
		
		
		function unlockQuestionsFields(){
			$('input[id^=id_pergunta_set-]').removeClass("disabled");
			$('input[id^=id_pergunta_set-]').attr("disabled", false);
			$('.field-data').find("span.datetimeshortcuts").removeClass("disabled");
		}
		
		function createConfirm(){
			$("#custom_confirm").dialog({
				resizable: false,
				height:140,
				modal: true,
				buttons: {
					"Sim": function() {
						$(this).dialog("close");
						callback(true);
					},
					"Não": function() {
						$(this).dialog("close");
						callback(false);
					}
				}
			});
		}
		
		function createEditConfirm(){
			$("#custom_edit_confirm").dialog({
				resizable: false,
				height:150,
				modal: true,
				buttons: {
					"Sim": function() {
						$(this).dialog("close");
						editCallback(true);
					},
					"Não": function() {
						$(this).dialog("close");
						editCallback(false);
					}
				}
			});
		}
		
		function createAlert(){
			$('#custom_alert').dialog({
										modal:true,
										resizable:false,
									  	buttons:{
									  			Ok:function(){
												       $(this).dialog("close");
												}
									    }
									  });
		}
		
		function changeSubmitBehavior(){
			$('#chamado_form').submit(function(e) {
				var flag = false;
				var perguntas = $('textarea[id^=id_pergunta_set-]');
				for(var i=0; i<perguntas.length; i++){
					if(perguntas[i].value.toString() != ''){
						flag = true;
						break;
					}
				}
				if(flag){
					createConfirm();
				}
				else{
					createAlert();
				}
				e.preventDefault();
        		return false;
			});}
			
		function callback(value){
			if(value){
				unlockAddFields();
   				
   			}
		}
		
		function enableAccordion(){
        	$('div.inline-group div.inline-related:not(.tabular):not(.empty-form)').each(function() {
		        fs = $(this).find('fieldset')
		        h3 = $(this).find('h3:first')
		
		        // Don't collapse if fieldset contains errors
		        if (fs.find('div').hasClass('errors'))
		            fs.addClass('stacked_collapse');
		        else
		            fs.addClass('stacked_collapse collapsed');
		        
		        // Add toggle link
		        h3.prepend('<a class="stacked_collapse-toggle" href="#">(' + gettext('Show') + ')</a> ');
		        h3.find('a.stacked_collapse-toggle').bind("click", function(){
		            fs = $(this).parent('h3').next('fieldset');
		            if (!fs.hasClass('collapsed'))
		            {
		                fs.addClass('collapsed');
		                $(this).html('(' + gettext('Show') + ')');
		                
		            }
		            else
		            {
		                fs.removeClass('collapsed');
		                $(this).html('(' + gettext('Hide') + ')');
		                var descricao = $(this).parent().parent().find('fieldset').find('div.field-descricao > div > textarea');
		                descricao.attr("disabled", 'disabled');
		                descricao.addClass("disabled");
		                
		                var data_input = $(this).parent().parent().find('fieldset').find('div.field-data > div > input');
		                data_input.attr("disabled", 'disabled');
		                data_input.addClass("disabled");
		                
		                var data_span = $(this).parent().parent().find('fieldset').find('div.field-data > div > span');
		                data_span.addClass("disabled");
		                
		                
		                //var inlines = $(this).parent().parent('div');
		                //lockQuestionDate(question);
		            }
		        }).removeAttr('href').css('cursor', 'pointer');
		      });
    	}
    	
    	function checkStatus(){
    		var status = document.getElementById("id_status");
        	var selected_status = status.options[status.selectedIndex].innerHTML;
    		if(selected_status == 'Fechado'){
    			$('div.add-row').addClass("disabled");
    		}
    	}
    	
    	
    	function handleFields(){
    		var user_type;
    		var username = '{{ user.username }}'
    		$.ajax({
                type: 'POST',
                url: '/user_type/',
                data: {'user_name':username},
                success: function(data) {
                	user_type = jQuery.parseJSON(data);
                	var status = document.getElementById("id_status");
        			var selected_status = status.options[status.selectedIndex].innerHTML;
                	
                	if(user_type == 'cliente'){
                		$('#id_status').addClass('disabled');
                		$('#id_status').attr("disabled", 'disabled');
                		
                		if(selected_status == 'Fechado'){
                			$('#id_fechamento').addClass('disabled');
                			$('#id_fechamento').attr("disabled", 'disabled');
                			$('#id_fechamento').parent().find('span').addClass("disabled");
                		}
                		else{
                			$('div.field-fechamento').addClass("disabled");
                		}
                		
                	}
                	else if(user_type == 'atendente'){
                		if(selected_status == 'Fechado'){
                			$('#id_status').addClass('disabled');
                			$('#id_status').attr("disabled", 'disabled');
                			$('#id_fechamento').addClass('disabled');
                			$('#id_fechamento').attr("disabled", 'disabled');
                			$('#id_fechamento').parent().find('span').addClass("disabled");
                		}
                	}
                }
        	});
    	}
    	
    	function changeEditSubmition(){
			$('#chamado_form').submit(function(e) {
				createEditConfirm();
				e.preventDefault();
        		return false;
			});}
			
		function editCallback(value){
			if(value){
				checkForInvalid();
   			}
		}
		
		function createBlankAlert(){
			$('#custom_blank_alert').dialog({
				modal:true,
				resizable:false,
			  	buttons:{
			  			Ok:function(){
						       $(this).dialog("close");
						}
			    }
			  });
		}
		
		
		function checkForInvalid(){
			var value = true;
			perg_resp = $('textarea');
			for(var i=0; i<perg_resp.length; i++){
				if(perg_resp[i].name.search("__prefix__") == -1){
					if(perg_resp[i].value == ''){
						value = false;
						break;
					}
				}
			}
			if(value == true){
				unlockEditFields();
			}
			else{
				createBlankAlert();
			}
			//verificar se tem pergunta ou resposta em branco
			//se tiver, exibe alerta e nao submete form
			//se nao tiver, chama unlock edit fields
		}
    	
    	function backCallback(value){
    		if(value){
	    		window.location = '/admin/atendimento_cliente/chamado/';
	    	}
    	}
    	
    	function createBackConfirm(){
			$("#back_confirm").dialog({
				resizable: false,
				height:160,
				modal: true,
				buttons: {
					"Sim": function() {
						$(this).dialog("close");
						backCallback(true);
					},
					"Não": function() {
						$(this).dialog("close");
						backCallback(false);
					}
				}
			});
		}
    	
    	function handleButtons(){
    		var status = document.getElementById("id_status");
        	var selected_status = status.options[status.selectedIndex].innerHTML;
        	if(selected_status == "Fechado"){
        		$('input[name=_save]')[0].id = "save";
				$('#save').addClass("disabled");	
        	}
        	else{
    			var save = document.getElementsByName("_save")[0];
    			save.value = "Salvar modificações"
    		}
    		$('.submit-row').append('<input class="back-button" type="button" value="Voltar" onclick="javascript:createBackConfirm()">');
    	}
    	
		
	-->
	</script>
{% endblock %}

